<template>
	<view class="left bai clearfix">
		
		<view class="left bai clearfix">
			
			<!--图片样式-->
			<view class="img-box left clearfix">
				<view class="img-top-label left clearfix">
					<label v-if="item.app_title">{{item.app_title}}</label>
					<label v-if="item.proportion">{{item.proportion}}</label>
					<label v-else-if="!item.proportion && item.size">{{item.size}}</label>
					<label v-if="item.video_duration">{{item.video_duration}}s</label>
					<label v-if="item.create_date"><uni-dateformat format="yyyy-MM-dd hh:mm" :date="item.create_date"></uni-dateformat></label>
					<label style="cursor:pointer;" @click="copyContent(item.content)"><uni-icons type="icon-fuzhi5" style="cursor: pointer;" title="复制内容" color="#666" size="15" custom-prefix="iconfont"></uni-icons></label>
					<view class="right works-more clearfix relative" title="发布" v-if="item.is_publish == false">
						<uni-icons type="icon-shangchuan5" color="#2979ff" title="发布" size="20" custom-prefix="iconfont"></uni-icons>
					</view>
				</view>
				
				<view class="img-content left relative clearfix ellipsis2 truncate-2-lines">
					{{item.content}}
				</view>
				
				<view class="works-contents left clearfix" v-if="item.type=='video' || item.type=='oral' || item.type=='baidu-video'">
					
					<view class="video-type-play left clearfix relative" v-if="!data.video_url" :style="'width:'+imageSize.width+'px;height:'+imageSize.height+'px;background:#efefef;'">
						<zmt-colorful-ring :width="70" :text="data.task_status_text=='执行成功'?'优化中':data.task_status_text"></zmt-colorful-ring>
						<view class="video-play-time absolute left clearfix">
							大约需要2-5分钟
						</view>
					</view>
					
					<view class="video-type-play left clearfix" v-else :style="'width:'+imageSize.width+'px;height:'+imageSize.height+'px;overflow:hidden;'">
						<image :src="data.webp_url" @click="previewImage(item)" :style="imageShow==false?'display:none;border-radius:5px;':'display:block;border-radius:5px;width:'+imageSize.width+'px;height:'+imageSize.height+'px'" :radius="10" @load="setImageShowStatus()" mode="aspectFit">
						</image>
						
					</view>
					
					
					
					<view class="works-buttons left clearfix">
						<label style="margin-left:0px;" @click="downloadFile(item.video_url,item.app_title)">
							<uni-icons type="icon-xiazai17" style="cursor: pointer;" title="下载" color="#999" size="25" custom-prefix="iconfont"></uni-icons>
						</label>
						<label>
							<uni-icons type="icon-shuaxin4" style="cursor: pointer;" title="复制" color="#999" size="25" custom-prefix="iconfont"></uni-icons>
						</label>
						<label>
							<uni-icons type="icon-fenxiang18" style="cursor: pointer;" title="分享" color="#999" size="25" custom-prefix="iconfont"></uni-icons>
						</label>
						<label @click="alertRemove(item,index)">
							<uni-icons type="icon-shanchu3" style="cursor: pointer;" title="删除" color="#999" size="23" custom-prefix="iconfont"></uni-icons>
						</label>
					</view>
				</view>
				
				
				<view class="works-contents left clearfix" v-if="item.type=='image'">
					<image :src="item.video_url" @click="previewImage(item)" mode="aspectFit" :style="'width:'+imageSize.width+'px;height:'+imageSize.height+'px'"></image>
					<view class="works-buttons left clearfix">
						<label style="margin-left:0px;" @click="downloadFile(item.video_url,item.app_title)">
							<uni-icons type="icon-xiazai17" style="cursor: pointer;" title="下载" color="#999" size="25" custom-prefix="iconfont"></uni-icons>
						</label>
						<label>
							<uni-icons type="icon-shuaxin4" style="cursor: pointer;" title="复制" color="#999" size="25" custom-prefix="iconfont"></uni-icons>
						</label>
						<label>
							<uni-icons type="icon-fenxiang18" style="cursor: pointer;" title="分享" color="#999" size="25" custom-prefix="iconfont"></uni-icons>
						</label>
						<label @click="alertRemove(item,index)">
							<uni-icons type="icon-shanchu3" style="cursor: pointer;" title="删除" color="#999" size="23" custom-prefix="iconfont"></uni-icons>
						</label>
					</view>
				</view>
			</view>
			
		</view>

	<!--预览图片和视频弹窗-->
	<uni-popup ref="imgPopup" type="center">
		<view class="img-popup-box left clearfix">
			<view class="img-pop-title left clearfix">
				<view class="img-pop-title-left left">
					预览
				</view>
				<view class="img-pop-title-right right"  @click="this.$refs.imgPopup.close()">
					<uni-icons type="closeempty" size="20" color="#666"></uni-icons>
				</view>
			</view>
			
			<view class="img-pop-content left clearfix" v-if="itemType=='image'">
				<image :src="previewImageUrl" mode="aspectFit" style="width:100%;height:100%;border-radius: 5px;"></image>
			</view>
			
			<view class="img-pop-content left clearfix" v-if="itemType=='video' || item.type=='oral'">
				<video :autoplay="true" :loop="true" :src="previewImageUrl" mode="aspectFit" style="width:100%;height:100%;border-radius: 5px;"></video>
			</view>
			
			<view class="im-pop-close-button right">
				<view class="im-pop-button right">
					创作相似
				</view>
				<view class="im-pop-button2 right" @click="this.$refs.imgPopup.close()">
					取消
				</view>
			</view>
		</view>
	</uni-popup>
	<up-modal :show="showRemove" @cancel="showRemove = false" @confirm="remove()" :showCancelButton="true" title="删除确认" content="确认要删除吗？"></up-modal>
	</view>
</template>

<style scoped>
	.im-pop-button2{width:80px;height:35px;border:1px solid #ddd;line-height:35px;font-size:13px;color:#333;text-align: center;border-radius: 5px;margin-top:7.5px;cursor:pointer;}
	.im-pop-button{width:90px;height:35px;background:#2979ff;line-height:35px;font-size:13px;color:#fff;text-align: center;border-radius: 5px;margin-top:7.5px;cursor:pointer;margin-left:20px;}
	.img-pop-content image{border-radius: 5px;}
	.im-pop-close-button{width:90%;height:50px;line-height:50px;margin-right:2%;margin-top:30px;text-align: center;}
	.img-pop-content{width:96%;height:500px;margin-left:2%;margin-top:30px;background:#efefef;}
	.img-pop-title-right{margin-right:10px;margin-top:5px;cursor:pointer;}
	.img-pop-title-left{line-height:40px;font-size:16px;margin-left:20px;}
	.img-pop-title{width:100%;height:40px;margin-top:5px;}
	.img-popup-box{width:950px;height:680px;background:#fff;border-radius: 12px;}
	.works-contents image{border-radius: 5px;cursor:pointer;}
	.video-type-play image{width:100%;height:100%;border-radius: 10px;}
	.video-play-time{font-size:12px;color:#999;bottom:1rem;text-align: center;width:100%;}
	.gradient-flow {width: 100vw;height: 100vh;background-size: 200% 200%;background-image: linear-gradient(135deg, #ff7c7c, #4465f2, #7e57c2, #7e57c2);animation: flow 3s ease infinite;}
	@keyframes flow {0% { background-position: 0% 50%; }
	  50% { background-position: 100% 50%; }
	  100% { background-position: 0% 50%; }
	}
	.video-bili{font-size:.65rem;line-height:1.2rem;text-align: center;padding-left:.5rem;padding-right:.5rem;background-color: rgba(255, 255, 255, 0.1);border-radius: 5px;color:#999;margin-left:.5rem;margin-top:.5rem;font-weight:400;}
	.video-type-play{margin-top:.8rem;border-radius: 10px;}
	.works-buttons label{float:left;margin-left:20px;line-height:40px;}
	.works-buttons{width:100%;height:40px;margin-top:10px;}
	.works-items image{width:100%;height:100%;}
	.works-items{margin:10px;border-radius: 10px;overflow: hidden;}
	.works-contents{width:100%;min-height:100px;}
	.works-more{margin-right:20px;cursor:pointer;}
	.img-content{width:calc(100% - 40px);padding:20px;color:#666;max-height:28px;padding-left:0px;margin-bottom:20px;}
	.img-top-label label{padding-left:10px;padding-right:10px;float:left;line-height:30px;background:rgb(217,229,242,.5);border-radius: 3px;margin-right:10px;font-size:13px;color:#777;}
	.img-top-label{width:100%;line-height:30px;height:30px;}
	.img-box{width:100%;}
</style>

<script>
	var db = uniCloud.database();
	var aliyun = uniCloud.importObject('aliyun',{customUI:true});
	var baidu = uniCloud.importObject('baidu',{customUI:true});
	var application = uniCloud.importObject('application',{customUI:true});
	var global = uniCloud.importObject('global',{customUI:true});
	export default {
		name:"works-list",
		data() {
			return {
				taskStatus:null,
				videoContext:null,
				item:{},
				imageSize:{},
				imageShow:false,
				isDelShow:false,
				isShowDetail:false,
				previewImageUrl:'',//预览图片地址
				removeItem:{},
				showRemove:false,
				itemType:'',
				baiduAccessToken:''
			};
		},
		props:{
			data:{
				type:Object,
				default:{}
			},
			index:{
				type:Number,
				default:null
			}
		},
		watch:{
			"data"(val){
				this.item = val;
				this.checkItem(val);
				uni.pageScrollTo({
				        scrollTop: 0,
				        duration: 0,
				    });
			}
		},
		mounted() {
			var that = this;
			var item = this.data;
			setTimeout(function(){
				that.checkItem(item);
			},500);
			
			this.item = item;
			this.getBaiduAccessToken();
		},
		methods:{
			//下载
			downloadFile(url, fileName) {
			    // 创建一个新的 URL 对象，添加 download 参数
			        const newUrl = new URL(url);
			        newUrl.searchParams.append('download', fileName);
			        // 在新窗口中打开链接
			        window.open(newUrl.toString(), '_blank');
			},
			//出来内容
			async checkItem(item){
				var that = this;
				if(item.webp_static_url || item.video_url){
					if(item.type == 'video' || item.type==	'oral'){
						var imageInfo = await that.getImageInfo(item.webp_static_url);
					}else if(item.type == 'image'){
						var imageInfo = await that.getImageInfo(item.video_url);
					}
					var width = imageInfo.width;
					var height = imageInfo.height;
				}else{
					var size = item.size.split('*');
					var width = size[0];
					var height = size[1];
				}
				
				
				if(width > height && height > 300){
					var imageHeight = 300;
					var imageWidth = width * (300/height);
				}else if(width == height && width > 300){
					var imageHeight = 300;
					var imageWidth = 300;
				}else if(width < height && width > 300){
					var imageWidth = 300;
					var imageHeight = height * (300/width);
				}else{
					var imageWidth = width;
					var imageHeight = height;
				}
						var imgSize = {
							width:parseInt(imageWidth),
							height:parseInt(imageHeight)
						}
					console.log('图片信息',imgSize);
					that.imageSize = imgSize;
					
					if(item.type!='baidu-video'){
						if(item.task_status!='SUCCEEDED' && item.task_status!='FAILED' && item.task_status!='UNKNOWN'){
							this.getTaskReuslt(item);
						}else if(!item.video_url){
							this.getTaskReuslt(item);
						}
					}else{
						//调用百度视频获取结果
						if(item.task_status==0 && item.task_status==3){
							this.getBaiduVideoReuslt(item);
						}else if(!item.video_url){
							this.getBaiduVideoReuslt(item);
						}
					}
					
			},
			//获取百度视频结果
			getBaiduVideoReuslt(item){
				var that = this;
				var jobId = item.task_id;
				var token = this.baiduAccessToken;
				console.log('jobid',jobId);
				if(jobId && token){
					setInterval(function(){
						baidu.getVideoResultFromJobid(jobId,token).then(res=>{
							console.log('res',res);
						}).catch(err=>{
							console.log('返回失败',err);
						});
					},60000);
				}
				
			},
			//获取图片属性
			getImageInfo(imagePath){
				 return new Promise((resolve, reject) => {
				        uni.getImageInfo({
				            src: imagePath,
				            success: function (res) {
				                resolve(res);
				            },
				            fail: function (err) {
				                reject(err);
				            }
				        });
				    });
			},
			//删除
			remove(){
				var that = this;
				var removeItem = that.removeItem;
				var item = removeItem.item;
				var index = removeItem.index;
				if(item && item._id){
					uni.showLoading({
						title:'删除中'
					})
					db.collection('create_result').where({_id:item._id}).remove().then(res=>{
						uni.hideLoading()
						uni.showToast({
							title:'删除成功',
							icon:'none',
							duration:2000
						})
						var result = res.result.deleted;
						that.showRemove = false;
						if(result == 1){
							that.$emit('confirm',index);
						}
					}).catch(err=>{
						uni.hideLoading()
					});
				}
			},
			//弹出删除确认框
			alertRemove(item,index){
				var that = this;
				that.showRemove = true;
				that.removeItem = {
					item:item,
					index:that.index
				}
			},
			//预览图片
			previewImage(item){
				this.itemType = item.type;
				this.previewImageUrl = item.video_url;
				this.$refs.imgPopup.open();
			},
			//获取百度token
			getBaiduAccessToken(){
				baidu.getAccessToken().then(res=>{
					this.baiduAccessToken = res.result.access_token;
				});
			},
			copyContent(content) {
			            // 要复制的文本内容
			            const textToCopy = content;
			            // 调用 uni.setClipboardData 方法将文本复制到剪贴板
			            uni.setClipboardData({
			                // 要复制的文本
			                data: textToCopy,
			                // 复制成功的回调函数
			                success: function () {
			                    // 显示成功提示
			                    uni.showToast({
			                        title: '复制成功',
			                        icon: 'success'
			                    });
			                }
			            });
			        },
			//图片加载完执行
			setImageShowStatus(){
				this.imageShow = true;
			},
			//获取生成结果
			getTaskReuslt(data){
				var that = this;
					var taskId = data.task_id;
					var index = this.index;
					var interval = setInterval(function(){
						if(taskId){
							aliyun.getWenshengVideoTaskResult(taskId).then(res=>{
								var output = res.result.data.output;
								var usage = res.result.data.usage;
								data.task_status = output.task_status;//状态
								if(that.taskStatus!='SUCCEEDED' && that.taskStatus!='FAILED' && that.taskStatus!='UNKNOWN'){
								switch(data.task_status){
									case 'PENDING':
									data.task_status_text = '排队中';
									break;
									case 'RUNNING':
									data.task_status_text = '生成中';
									break;
									case 'SUSPENDED':
									data.task_status_text = '任务挂起';
									break;
									case 'SUCCEEDED':
									data.task_status_text = '执行成功';
									break;
									case 'FAILED':
									data.task_status_text = '执行失败';
									break;
									case 'UNKNOWN':
									data.task_status_text = '状态未知';
									break;
								}
								data.submit_time = output.submit_time;//任务提交时间
								data.scheduled_time = output.scheduled_time;//任务执行时间
								data.end_time = output.end_time;//任务完成时间
								if(output.code || output.message){
									data.code = output.code;
									data.message = output.message;
								}
								if(usage){
									data.video_duration = usage.video_duration;//视频时长
								}
								var id = data._id;//当前记录的id
								//如果当前返回结果的状态与上次的状态不同的话，则更新到数据库
								if(data.task_status != that.taskStatus && id){
									that.updateDataToDatabase(data,id,index);
								}
								that.taskStatus = data.task_status;
								}else{
								 clearInterval(interval);
								 if(that.taskStatus=='SUCCEEDED'){
									 var videoUrl = output.video_url;//视频地址
									//获取视频文件链接
									that.getVideoResult(data,index,videoUrl);
								 }
								}
							}).catch(err=>{
								application.createLog({
									type:'文生视频',
									content:'创建task_id失败,'+JSON.stringify(err)
								})
							});
						}
					},3000); 
					
			},
			
			
			//获取视频链接地址
			getVideoResult(data,index,videoUrl){
				var that = this;
				var taskId = data.task_id;
				var size = data.size;
				var id = data._id;
				aliyun.getVideoResult(videoUrl,taskId,size,id).then(res=>{
					console.log('查询结果',res);
					if(res.code == 200){
						var result = res.result;
						data.video_url = result.video_url;
						data.video_small_url = result.video_small_url;
						data.webp_url = result.webp_url;
						data.webp_static_url = result.webp_static_url;
						that.$emit('updateStatus',{item:data,index:index});
					}
				}).catch(err=>{
					console.log('err',err);
					application.createLog({
						type:'文生视频',
						content:'根据task_id获取视频结果失败,'+JSON.stringify(err)
					})
				});
			}, 
			//更新数据到数据库
			updateDataToDatabase(data,id,index){
				var that = this;
				global.updateData('create_result',{_id:id},data).then(res=>{
					that.$emit('updateStatus',{item:data,index:index});
				}).catch(err=>{
					application.createLog({
						type:'文生视频',
						content:'根据task_id获取视频结果更新到数据库失败,'+JSON.stringify(err)
					})
				});
			}
			
		}
	}
</script>
